package cn.iocoder.yudao.module.enterprise.service.emissionsource;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.carbon.api.gas.GasApi;
import cn.iocoder.yudao.module.carbon.api.gas.dto.GasRespDTO;
import cn.iocoder.yudao.module.carbon.api.gwp.GwpApi;
import cn.iocoder.yudao.module.carbon.api.gwp.dto.GwpListReqDTO;
import cn.iocoder.yudao.module.carbon.api.gwp.dto.GwpRespDTO;
import cn.iocoder.yudao.module.enterprise.controller.admin.emissionsource.vo.*;
import cn.iocoder.yudao.module.enterprise.convert.emissionsource.EmissionGaseConvert;
import cn.iocoder.yudao.module.enterprise.convert.emissionsource.EmissionSourceConvert;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.emissionsource.EmissionGaseDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.emissionsource.EmissionSourceDO;
import cn.iocoder.yudao.module.enterprise.dal.mysql.emissionsource.EmissionGaseMapper;
import cn.iocoder.yudao.module.enterprise.dal.mysql.emissionsource.EmissionSourceMapper;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.EMISSION_SOURCE_NOT_EXISTS;

/**
 * 排放源 Service 实现类
 *
 * @author StevenShen
 */
@Service
@Validated
public class EmissionSourceServiceImpl implements EmissionSourceService {

    @Resource
    private EmissionSourceMapper emissionSourceMapper;
    @Resource
    private EmissionGaseMapper emissionGaseMapper;
    @Resource
    private GasApi gasApi;
    @Resource
    private GwpApi gwpApi;
    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public Long createEmissionSource(EmissionSourceCreateReqVO createReqVO) {
        // 插入
        EmissionSourceDO emissionSource = EmissionSourceConvert.INSTANCE.convert(createReqVO);
        emissionSourceMapper.insert(emissionSource);
        Long id = emissionSource.getId();

        List<EmissionGaseDO> emissionGaseDOList = EmissionGaseConvert.INSTANCE.convertList(createReqVO.getEmissionGaseList());
        emissionGaseDOList = emissionGaseDOList.stream().map(emissionGaseDO -> emissionGaseDO.setEmissonId(id)).collect(Collectors.toList());
        emissionGaseMapper.insertBatch(emissionGaseDOList);
        // 返回
        return id;
    }

    @Override
    public void updateEmissionSource(EmissionSourceUpdateReqVO updateReqVO) {
        Long id = updateReqVO.getId();
        // 校验存在
        validateEmissionSourceExists(id);

        // 删除排放源和温室气体关联
        emissionGaseMapper.deleteByEmissionId(id);
        // 插入排放源和温室气体关联表
        List<EmissionGaseUpdateReqVO> emissionGaseList = updateReqVO.getEmissionGaseList();
        List<EmissionGaseDO> emissionGaseDOList = EmissionGaseConvert.INSTANCE.convertList03(emissionGaseList);
        emissionGaseDOList = emissionGaseDOList.stream().map(emissionGaseDO -> emissionGaseDO.setEmissonId(id)).collect(Collectors.toList());
        emissionGaseMapper.insertBatch(emissionGaseDOList);

        // 更新排放源表
        EmissionSourceDO updateObj = EmissionSourceConvert.INSTANCE.convert(updateReqVO);
        emissionSourceMapper.updateById(updateObj);
    }

    @Override
    public void deleteEmissionSource(Long id) {
        // 校验存在
        validateEmissionSourceExists(id);
        // 删除
        emissionSourceMapper.deleteById(id);
    }

    private void validateEmissionSourceExists(Long id) {
        if (emissionSourceMapper.selectById(id) == null) {
            throw exception(EMISSION_SOURCE_NOT_EXISTS);
        }
    }

    @Override
    public EmissionSourceRespVO getEmissionSource(Long id) {
        // 获取排放源信息
        EmissionSourceDO emissionSourceDO = emissionSourceMapper.selectById(id);
        EmissionSourceRespVO respVO = EmissionSourceConvert.INSTANCE.convert(emissionSourceDO);
        if (respVO == null) {
            return null;
        }

        // 获取温室气体列表
        List<GasRespDTO> gasList = gasApi.getGasList().getCheckedData();
        // 获取排放气体列表
        List<EmissionGaseDO> emissionGaseDOList = emissionGaseMapper.selectListByEmissionId(id);
        // 获取GWP值
        List<GwpRespDTO> gwpList = gwpApi.getGwpList(new GwpListReqDTO().setReportVersion(emissionSourceDO.getGwp())).getCheckedData();

        // 合并列表
        List<EmissionGaseRespVO> list = new ArrayList<>();
        for (GasRespDTO gas : gasList) {
            EmissionGaseRespVO emissionGase = new EmissionGaseRespVO();
            emissionGase.setCategory(gas.getCategory());
            emissionGase.setName(gas.getName());
            emissionGase.setGaseId(gas.getId());
            list.add(emissionGase);
        }

        list = list.stream().map(e1 -> {
            for (EmissionGaseDO e2 : emissionGaseDOList) {
                if (e2.getGaseId().equals(e1.getGaseId())) {
                    e1.setValue(e2.getValue())
                            .setUnitLeft(e2.getUnitLeft())
                            .setUnitRight(e2.getUnitRight());
                }
            }
            for (GwpRespDTO e3 : gwpList) {
                if (e3.getGaseId().equals(e1.getGaseId())) {
                    e1.setGwp(e3.getGwp());
                }
            }
            return e1;
        }).collect(Collectors.toList());

        respVO.setEmissionGaseList(list);

        return respVO;
    }

    @Override
    public PageResult<EmissionSourceDO> getEmissionSourcePage(EmissionSourcePageReqVO pageReqVO) {
        PageResult<EmissionSourceDO> pageResult = emissionSourceMapper.selectPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return new PageResult<>(pageResult.getTotal());
        }

        List<EmissionSourceDO> list = pageResult.getList();
        list = list.stream().map(e -> {
            AdminUserRespDTO user = adminUserApi.getUser(Long.parseLong(e.getUpdater())).getCheckedData();
            // 查询更新人
            e.setUpdater(user.getNickname());
            return e;
        }).collect(Collectors.toList());

        return new PageResult<>(list, pageResult.getTotal());
    }

    @Override
    public List<EmissionSourceDO> getEmissionSourceList(EmissionSourceExportReqVO exportReqVO) {
        return emissionSourceMapper.selectList(exportReqVO);
    }

    @Override
    public List<EmissionSourceDO> getEmissionSourceList(Collection<Long> ids) {
        return emissionSourceMapper.selectBatchIds(ids);
    }

}
